import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:async';
import 'dart:convert';
import 'constants.dart';
import 'network_manager.dart';
import 'user_model.dart';
import 'userModelSingleton.dart';
class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();
  bool _isButtonEnabled = false;
  bool _isCodeButtonEnabled = true;
  String _codeButtonText = '获取验证码';
  Timer? _timer;
  int _start = 60;
  @override
  void initState() {
    super.initState();
    _phoneController.addListener(_validateInputs);
    _codeController.addListener(_validateInputs);
  }
  void _validateInputs() {
    setState(() {
      _isButtonEnabled = (
          _phoneController.text.length == 11
              && _codeController.text.length == 4
      );
    });
  }
  @override
  void dispose() {
    _phoneController.dispose();
    _codeController.dispose();
    _timer?.cancel();
    super.dispose();
  }
  // 获取验证码
  Future<void> _getCode() async {
    final String phone = _phoneController.text;
    if (phone.isEmpty || phone.length != 11) {
      print('请输入正确的手机号');
      return;
    }
    setState(() {
      _isCodeButtonEnabled = false;
      _startTimer();
    });
    NetworkManager().get(
      '$baseUrl$get_verification_code_url',
      {'userphone': phone},
          (data) {
        print('验证码发送成功');
        print('后台返回数据: $data');
      },
          (error) {
        print('验证码发送失败');
        print('错误信息: $error');
        setState(() {
          _isCodeButtonEnabled = true;
          _timer?.cancel();
          _codeButtonText = '获取验证码';
        });
      },
    );
  }
  void _startTimer() {
    _start = 60;
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        if (_start == 0) {
          _timer?.cancel();
          _isCodeButtonEnabled = true;
          _codeButtonText = '获取验证码';
        } else {
          _start--;
          _codeButtonText = '${_start}s';
        }
      });
    });
  }
  Future<void> _login(BuildContext context) async {
    final String phone = _phoneController.text;
    final String code = _codeController.text;
    var  params =  {'userphone': phone, 'ucode': code};
    NetworkManager().get('$baseUrl$login_url', params, (data) {
        if (data['code'] == 0) {
          print('登录成功');
          print('后台返回数据: $data');
          // 将数据存储到单例模型中
          UserModelSingleton().userModel = UserModel.fromJson(data['data']);
          // 打印用户名
          print('用户名userphone: ${UserModelSingleton().userModel?.userphone}');
          print('mybatisRecordCount: ${UserModelSingleton().userModel?.mybatisRecordCount}');
          Navigator.of(context).pushReplacementNamed("app");
        } else {
          print('登录失败');
          print('后台返回数据: $data');
          Fluttertoast.showToast(
            msg: data['msg'] ?? "登录失败，请检查您的手机号和验证码",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.BOTTOM,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.red,
            textColor: Colors.white,
            fontSize: 16.0,
          );
        }
      },
          (error) {
        print('登录失败');
        print('错误信息: $error');
        Fluttertoast.showToast(
          msg: "登录失败，请检查您的手机号和验证码",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0,
        );
      },
    );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              SizedBox(height: 120),
              Text(
                '您好，\n欢迎来到留意营业厅',
                style: TextStyle(fontSize: 24),
                textAlign: TextAlign.left,
              ),
              SizedBox(height: 20),
              TextField(
                controller: _phoneController,
                keyboardType: TextInputType.number,
                inputFormatters: [
                  FilteringTextInputFormatter.digitsOnly,
                  LengthLimitingTextInputFormatter(11),
                ],
                decoration: InputDecoration(
                  hintText: '请输入收货人手机号',
                  border: InputBorder.none,
                ),
              ),
              SizedBox(height: 8),
              Divider(
                thickness: 1,
                indent: 8,
                endIndent: 8,
              ),
              SizedBox(height: 8),
              Row(
                children: <Widget>[
                  Expanded(
                    child: TextField(
                      controller: _codeController,
                      keyboardType: TextInputType.number,
                      inputFormatters: [
                        FilteringTextInputFormatter.digitsOnly,
                        LengthLimitingTextInputFormatter(4),
                      ],
                      decoration: InputDecoration(
                        hintText: '请填写验证码',
                        border: InputBorder.none,
                      ),
                    ),
                  ),
                  SizedBox(width: 8),
                  ElevatedButton(
                    onPressed: _isCodeButtonEnabled ? _getCode : null,
                    child: Text(_codeButtonText),
                  ),
                ],
              ),
              SizedBox(height: 8),
              Divider(
                thickness: 1,
                indent: 8,
                endIndent: 8,
              ),
              SizedBox(height: 200),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 15),
                child: SizedBox(
                  width: double.infinity,
                  height: 50,
                  child: ElevatedButton(
                    onPressed: _isButtonEnabled ? () => _login(context) : null,
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.resolveWith<Color>(
                            (Set<MaterialState> states) {
                          if (states.contains(MaterialState.disabled)) {
                            return Colors.grey;
                          }
                          return Colors.black;
                        },
                      ),
                      foregroundColor: MaterialStateProperty.resolveWith<Color>(
                            (Set<MaterialState> states) {
                          if (states.contains(MaterialState.disabled)) {
                            return Colors.black;
                          }
                          return Colors.white;
                        },
                      ),
                    ),
                    child: Text('登录'),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}